package vn.bang.utility;

import java.math.BigInteger;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class EncryptionUtil {

	public static String encrypt(final String str, final String algorithm) {
		String encrypted = "";
		try {
			final MessageDigest messageDigest = MessageDigest
					.getInstance(algorithm);
			messageDigest.reset();
			messageDigest.update(str.getBytes(), 0, str.length());
			encrypted = new BigInteger(1, messageDigest.digest()).toString(16);
		} catch (NoSuchAlgorithmException ex) {
			throw new IllegalArgumentException(
					String.format("Algorithm invalid: %d", algorithm));
		}
		return encrypted;
	}

	public static String encryptPasswordWithMD5Algorithm(final char[] password) {
		String encrypted = "";
		try {
			byte[] passwordBytes = Charset.forName("UTF-8").encode(CharBuffer.wrap(password)).array();
			
			final MessageDigest messageDigest = MessageDigest
					.getInstance(MD5_ALGORITHM);
			messageDigest.reset();
			messageDigest.update(passwordBytes, 0, password.length);
			encrypted = new BigInteger(1, messageDigest.digest()).toString(16);
		} catch (NoSuchAlgorithmException ex) {
			throw new IllegalArgumentException(
					String.format("Algorithm invalid: %d", MD5_ALGORITHM));
		}
		return encrypted;
	}
	
	public static String encryptPasswordWithMD5Algorithm(final String password) {
		String encrypted = "";
		try {
			final MessageDigest messageDigest = MessageDigest
					.getInstance(MD5_ALGORITHM);
			messageDigest.reset();
			messageDigest.update(password.getBytes(), 0, password.length());
			encrypted = new BigInteger(1, messageDigest.digest()).toString(16);
		} catch (NoSuchAlgorithmException ex) {
			throw new IllegalArgumentException(
					String.format("Algorithm invalid: %d", MD5_ALGORITHM));
		}
		return encrypted;
	}
	
	static public final String MD5_ALGORITHM = "MD5";
	static public final String SHA_1_ALGORITHM = "SHA-1";
	static public final String SHA_256_ALGORITHM = "SHA-256";
}
